<script setup>

import { ref, onMounted, watch } from 'vue'
import { cfindClazz, addClazzApi, selectClazzByIdApi, updateClazzByIdApi, deleteClazzByIdApi } from '../../api/clazz'
import { selectAllEmpInfo } from '../../api/emp'
import { ElMessage, ElMessageBox } from 'element-plus'

// 员工信息
let empList = ref([
  {
    id: '',
    name: '',
  }
])
// 班级表单数据
const clazzFormData = ref(
  {
    name: '',
    date: [],
    begin: '',
    end: '',
  }
)

watch(() => clazzFormData.value.date, (newValue) => {
  console.log(newValue)
  if (newValue && newValue.length == 2) {
    clazzFormData.value.begin = newValue[0]
    clazzFormData.value.end = newValue[1]
  } else {
    clazzFormData.value.begin = ''
    clazzFormData.value.end = ''
  }
})

// 班级表格数据
const clazzList = ref([])

// 分页信息
let currentPage = ref(1)
let pageSize = ref(10)
let total = ref(0)

// 对话框信息
let dialogFormVisible = ref(false)
let title = ref('')
let inputSize = ref('large')


// 保存班级  对话框数据
let dialogClazzFormData = ref({
  id: '',
  name: '',
  room: '',
  beginDate: '',
  endDate: '',
  masterId: '', //???
  subject: '',
  creatTime: '',
  updateTime: '',
})

// 下拉列表数据
const subjectData = ref([
  { name: 'java', value: 1 },
  { name: '前端', value: 2 },
  { name: '大数据', value: 3 },
  { name: 'Python', value: 4 },
  { name: 'Go', value: 5 },
  { name: '嵌入式', value: 6 },
])

// 校验表单
const rules = ref({
  name: [
    { required: true, message: '班级名称为必填项', trigger: 'blur' },
    { min: 4, max: 30, message: '班级名称长度应在4到30之间', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]+$/, message: '班级名称只能包含汉字、数字、字母', trigger: 'blur' }
  ],
  room: [
    { required: false, message: '班级教室为选填项', trigger: 'blur' },
    { min: 1, max: 20, message: '班级教室长度应在1到20之间', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]+$/, message: '班级教室只能包含汉字、数字、字母', trigger: 'blur' }
  ],
  beginDate: [
    { required: true, message: '开课时间为必填项', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '结课时间为必填项', trigger: 'change' }
  ],
  subject: [
    { required: true, message: '学科为必填项', trigger: 'change' }
  ]
})
// 表单验证规则
const ruleFormRef = ref()

// 标签与输入框的宽度
let formLabelWidth = '120px'


// 上面是数据
// ------------------------------------------------------
// ------------------------------------------------------
// ------------------------------------------------------
// ------------------------------------------------------
// ------------------------------------------------------
// 下面是函数






// 添加新增按钮点击事件
function addBut() {
  dialogFormVisible.value = true
  title.value = '新增班级'
}

// 添加编辑按钮点击事件
function editBut() {
  dialogFormVisible.value = true
  title.value = '修改班级'
}

// 添加删除按钮点击事件
function delBut(id) {
  ElMessageBox.confirm(
    '您确定要删除吗?',
    '删除部门',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const result = await deleteClazzByIdApi(id)
      if (result.code == 1) {
        ElMessage.success('删除成功!')
        search()
      } else {
        ElMessage.error(result.msg)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 分页函数
function handleSizeChange() {
  search()
}

function handleCurrentChange() {
  search()
}

// 查询所有班级
async function search() {
  const result = await cfindClazz(clazzFormData.value.name, clazzFormData.value.begin, clazzFormData.value.end, currentPage.value, pageSize.value)
  if (result == null) {
    ElMessage.error("前端返回值为空")
  }

  if (result.code) {
    total.value = result.data.total
    clazzList.value = result.data.rows
  } else {
    ElMessage.error("不对")
  }
}

// 查询员工信息
async function searchEmp() {
  const result = await selectAllEmpInfo()
  if (result == null) {
    ElMessage.error("前端返回值为空")
  }
  if (result.code == 1) {
    empList.value = result.data
    console.log(empList.value)
  } else {
    ElMessage.error("不对")
  }
}

// 清空查询表单数据   按钮
function clearClazzFormData() {
  clazzFormData.value = {
    name: '',
    date: [],
    begin: '',
    end: '',
  }
  search()
}

// 清空添加表单数据   按钮
function clearDialogClazzFormData() {
  dialogClazzFormData.value = {
    name: '',
    room: '',
    beginDate: '',
    endDate: '',
    masterId: '', //???
    subject: ''
  }
  ruleFormRef.value.resetFields()
}

// 新增、修改 班级
async function addClazz() {

  if (ruleFormRef) {
    await ruleFormRef.value.validate( async (valid) => {
      if (valid) {
        if (dialogClazzFormData.value.id) {
          // 修改
          const result = await updateClazzByIdApi(dialogClazzFormData.value)
          if (result.code == 1) {
            clearDialogClazzFormData()
            ElMessage.success('修改成功')
            dialogFormVisible.value = false
            search()
          } else {
            ElMessage.error(result.msg)
          }

        } else {
          // 新增
          const result = await addClazzApi(dialogClazzFormData.value)
          if (result.code == 1) {
            ElMessage.success('添加成功')
            dialogFormVisible.value = false
            search()
            clearDialogClazzFormData()
          } else {
            ElMessage.error(result.msg)
          }
        }
      } else {
        ElMessage.error('请填写正确的数据')
      }
    });
  }
}

// 根据id查询班级
async function selectClazzById(id) {
  const result = await selectClazzByIdApi(id)
  if (result.code == 1) {
    dialogClazzFormData.value = result.data
  } else {
    ElMessage.error(result.msg)
  }
}

// 根据id删除班级
async function deleteClazzById(id) {
  const result = await deleteClazzByIdApi(id)
  if (result.code == 1) {
    ElMessage.success('删除成功!')
    search()
  } else {
    ElMessage.error(result.msg)
  }
}

onMounted(() => {
  search()
  searchEmp()
})


</script>

<template>
  <h1>班级管理</h1>

  <!-- 条件查询表单 -->
  <div class="container">
    <!-- 条件查询表单 -->
    <!-- {{ clazzFormData }} -->
    <!-- <span v-for="(emp, index) in empList" :key="index">
      {{ emp.name }}
    </span> -->
    <el-form :inline="true" :data="clazzFormData" class="demo-form-inline">

      <!-- 班级名称输入框 -->
      <el-form-item label="班级名称">
        <el-input v-model="clazzFormData.name" placeholder="请输入班级名称" :size="inputSize" clearable />
      </el-form-item>

      <!-- 时间选择器 -->
      <el-form-item label="结束时间">
        <el-date-picker v-model="clazzFormData.date" type="daterange" range-separator="至" start-placeholder="开始时间"
          end-placeholder="结束时间" value-format="YYYY-MM-DD" :size="inputSize" />
      </el-form-item>

      <!-- 查询、清空 按钮 -->
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button type="info" @click="clearClazzFormData">清空</el-button>
      </el-form-item>

    </el-form>
  </div>

  <!-- 新增按钮 -->
  <div class="container">
    <el-button type="primary" @click="addBut"><el-icon style="margin-right: 10px;">
        <Plus />
      </el-icon>新增班级</el-button>
  </div>

  <!-- 表格 -->
  <div class="container">
    <!-- {{ clazzList }} -->
    <!-- {{ dialogClazzFormData }} -->
    <el-table :data="clazzList" border class="el-table">
      <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
      <el-table-column prop="name" label="班级名称" align="center"></el-table-column>
      <el-table-column prop="room" label="班级教室" align="center"></el-table-column>
      <el-table-column prop="masterName" label="班主任" align="center"></el-table-column>
      <el-table-column prop="beginDate" label="开课时间" align="center"></el-table-column>
      <el-table-column prop="endDate" label="结课时间" align="center"></el-table-column>
      <el-table-column prop="status" label="状态" align="center"></el-table-column>
      <el-table-column prop="updateTime" label="最后操作时间" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" @click="selectClazzById(scope.row.id); editBut()" size="small">编辑</el-button>
          <el-button type="danger" @click="delBut(scope.row.id)" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 分页条 -->
  <div class="container">
    <!-- {{ total }} -->
    <!-- {{ pageSize }}
    {{ currentPage }} -->
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 30]"
      :background=true layout="sizes, total, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </div>

  <!-- 对话框 -->
  <div class="container">

    <el-dialog v-model="dialogFormVisible" :title="title" width="600" draggable>
      <!-- {{ dialogClazzFormData }} -->

      <el-form ref="ruleFormRef" :model="dialogClazzFormData" :rules="rules"  label-position="left" >
        <!-- 班级名称 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="班级名称" prop="name" :label-width="formLabelWidth">
              <el-input v-model="dialogClazzFormData.name" autocomplete="off" placeholder="请输入班级名称" :size="inputSize" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 班级教室 -->
        <el-row :gutter="20">
          <el-col :span="24">

            <el-form-item label="班级教室" prop="room" :label-width="formLabelWidth">
              <el-input v-model="dialogClazzFormData.room" autocomplete="off" placeholder="请输入班级教室" :size="inputSize" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 开课时间 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <!-- 开课时间 -->
            <el-form-item label="开课时间" prop="beginDate" :label-width="formLabelWidth">
              <el-date-picker v-model="dialogClazzFormData.beginDate" type="date" placeholder="请选择开课时间"
                :size="inputSize" style="width: 100%;" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 结课时间 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="结课时间" prop="endDate" :label-width="formLabelWidth">
              <el-date-picker v-model="dialogClazzFormData.endDate" type="date" placeholder="请选择结课时间" :size="inputSize"
                style="width: 100%;" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
        </el-row>


        <!-- 班主任 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="班主任 &nbsp;&nbsp;&nbsp;" :label-width="formLabelWidth">
              <el-select v-model="dialogClazzFormData.masterId" placeholder="请选择班主任" style="width: 100%"
                :size="inputSize">
                <el-option v-for="(emp, index) in empList" :key="emp.id" :label="emp.name" :value="emp.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 学科 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="学科" prop="subject" :label-width="formLabelWidth">
              <el-select v-model="dialogClazzFormData.subject" placeholder="请选择学科" style="width: 100%"
                :size="inputSize">
                <el-option v-for="(subject, index) in subjectData" :key="index" :label="subject.name"
                  :value="subject.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 对话框按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="info" @click=" clearDialogClazzFormData(); dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="addClazz">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

</template>

<style scoped>
.container {
  margin: 20px 10px;
}

/* 表格边框加粗 - 使用更明显的颜色和宽度 */
:deep(.el-table) {
  border: 2px solid #d1d5da !important;
}

/* 加粗表格内部边框 - 使用更明显的颜色和宽度 */
:deep(.el-table td),
:deep(.el-table th) {
  border: 1px solid #dbe0e4 !important;
}

/* 表头边框可以更粗一些 */
:deep(.el-table th) {
  background-color: #eaebee !important;
  border-bottom: 2px solid #dee2e6 !important;
}
</style>